import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

import checkEnvVariable from '@/utils/checkEnvVariable';


// Check the variables
const API_URL = checkEnvVariable('DIRECTUS_URL') + 'graphql';
const AUTH_TOKEN = checkEnvVariable('DIRECTUS_TOKEN');

// Create link
const httpLink = createHttpLink({
    uri: API_URL
});

// Set up authentication context
const authLink = setContext((_, { headers }) => {
    const token = process.env.DIRECTUS_TOKEN;
    return {
        headers: {
        ...headers,
        authorization: `Bearer ${AUTH_TOKEN}`,
        },
    };
});

// Create Apollo Client
const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache(),
});

export default client;